import { User } from "@/entities/User";
import { initORM } from "@/utils";
import { getRandPassword } from "@/utils/base";
import { sendEmail } from "@/utils/email";
import { createMd5 } from "@/utils/hash";
import { NextApiRequest, NextApiResponse } from "next";

async function resetPassword(
  req: NextApiRequest,
  res: NextApiResponse<APIRes>
) {
  const { passResetToken, password } = req.body ?? {};

  const em = await initORM();
  const user = await em.findOne(User, { passResetToken });

  if (!user) {
    res
      .status(400)
      .json({ success: false, data: {}, message: "User not found" });
    return;
  }

  user.pass = createMd5(password);
  user.passResetToken = "";

  await em.persistAndFlush(user);

  res.status(200).json({
    success: true,
    data: user,
    message: "Password has been reseted, please log in",
  });
}

async function createUser(req: NextApiRequest, res: NextApiResponse<APIRes>) {
  const em = await initORM();
  const user = await em.create(User, req.body);
  await em.persistAndFlush(user);

  res.status(200).json({ success: true, data: {}, message: "User created" });
}

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<APIRes>
) {
  if (req.method === "POST") {
    resetPassword(req, res);
  } else {
    res
      .status(405)
      .json({ success: false, data: {}, message: "Method not allowed" });
  }
}
